package com.yeban.bams.server.serversocket;

import com.yeban.bams.service.Bank;
import com.yeban.bams.utils.ThreadPool;
import com.yeban.bams.utils.ThreadPoolConfig;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Desc 服务端
 * @Author yeban
 * @Date 2025/11/6
 */
public class BankServer {

    private ServerSocket serverSocket;  // 服务端套接字
    private Socket socket;              // 客户端套接字
    private boolean running = false;    // 服务端运行标识
    private ThreadPool pool;      // 自定义线程池

    public BankServer() {
        this.pool = new ThreadPool(ThreadPoolConfig.CORE_POOL_SIZE, ThreadPoolConfig.MAX_POOL_SIZE, ThreadPoolConfig.QUEUE_SIZE);
    }

    // 启动服务
    public void startServer() {
        try {
            serverSocket = new ServerSocket(8888);
            running = true;
            System.out.println("银行服务端启动成功！");

            while(running) {
                // 1.等待客户端接入
                socket = serverSocket.accept();
                System.out.println("客户端链接成功：" + socket.getRemoteSocketAddress());
                // 2.交由线程池处理
                pool.execute(new ServerTasker(socket));
            }
        } catch (IOException e) {
            System.out.println("服务器异常：" + e.getMessage());
        } finally {
            stopServer();
        }
    }

    // 关闭服务
    public void stopServer() {
        running = false;
        if(serverSocket != null && !serverSocket.isClosed()) {
            try {
                // 关闭服务端
                serverSocket.close();
                System.out.println("服务端已关闭！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        BankServer bankServer = new BankServer();
        bankServer.startServer();
    }
}
